<?php
require './model/Db.php';
require './model/Page.php';
$isMobile = preg_match('/mobile/i', $_SERVER['HTTP_USER_AGENT']);
if($isMobile){
	$css = [
		'public/css/my-bootstrap.min.css',
		'public/css/details.phone.min.css'
	];
}else{
	$css = [
		'public/css/my-bootstrap.min.css',
		'public/css/details.pc.min.css'
	];
}

$Db = Db::getInstance();
$user_data = $Db->islogin();

$isExist = $Db->find([
	table => ['content'],
	where => "id = {$_GET['cid']} and delete_time is NULL"
])[0];

if($isExist){
    $web_title = $isExist['title'];
    include './view/header.html';
    //维修、活动处理状态
    $wx = $Db->find([
    	table => ['gzwx'],
    	where => "cid = {$_GET['cid']}"
    ])[0];
    $hd = $Db->find([
    	table => ['hdsb'],
    	where => "cid = {$_GET['cid']}"
    ])[0];
  if($wx['is_deal']){
      $bdclass = $wx['is_do'] == 0?'noaccepted':'accepted';
      $do = true;
  }elseif($hd['is_deal']){
      $bdclass = $hd['is_do'] == 0?'unratified':'approval';
      $do = true;
  }else{
      $do = false;
  }
    
	//判断是否主题帖
	if($isExist['cid'] == 0){
		$isMain = true;
	}
	$cnt_where = $isMain ? "cid = {$_GET['cid']}" : "reply_id = {$_GET['cid']}";
	if(isset($_POST['submit'])){
	if($user_data){
		$_POST = $Db->escape($_POST);
		$paths = '';
		if($_POST['files']){
			foreach ($_POST['files'] as $value) {
				$paths .= '"'.$value.'",';
			}
			$paths = trim($paths,',');
		}
		$flag = null;
		if($isMain){
			$flag = $Db->save([
			table => 'content',
			map => [
				title => 'Re:'.$isExist['title'],
				body => $_POST['body'],
				mid => $isExist['mid'],
				cid => $_GET['cid'],
				file => '{"path":['.$paths.']}',
				uid => $user_data['id']
			]
			]);
			if($flag){
				$Db->update([
					table => 'content',
					map => [
						reply_num => '#reply_num+1#'
					],
					where => "id = {$_GET['cid']}"
				]);
			}
		}else{
			$flag = $Db->save([
				table => 'content',
				map => [
					title => $isExist['title'],
					body => $_POST['body'],
					mid => $isExist['mid'],
					reply_id => $_GET['cid'],
					file => '{"path":['.$paths.']}',
					uid => $user_data['id'],
					cid => $isExist['cid'],
				]
			]);
			if($flag){
				$Db->update([
					table => 'content',
					map => [
						reply_num => '#reply_num+1#'
					],
					where => "id in ({$_GET['cid']},{$isExist['cid']})"
				]);
			}
		}
		if($flag){ //加分
			$maxlv = 20+$user_data['job']*5;
			if($user_data['today_lv'] < $maxlv){
				if($user_data['today_lv']+2 > $maxlv){
					$diff = $user_data['today_lv']-$maxlv+2;
					$lv = "#lv+{$diff}#";
					$today_lv = $maxlv;
				}else{
					$lv = '#lv+2#';
					$today_lv = '#today_lv+2#';
				}
				$Db->update([
					table => 'bbs_user',
					map => [
						lv => $lv,
						today_lv => $today_lv
					],
					where => "id = {$user_data['id']}"
				]);
			}
		}
		
		$msg = $flag ? '回复成功' : '网络不稳定,请稍后再试~';
	}else{
		$msg = '请先登录,登录后才可以发帖哦~';
	}

	include './view/tip.html';
	}elseif(!isset($_GET['page'])){
		//浏览+1
		$Db->update([
			table => 'content',
			map => [
				look_num => '#look_num+1#'
			],
			where => "id = {$_GET['cid']}"
		]);
	}
	//获取本地表情
	$bq_arr = [];
	if(is_dir(EXP_FILE_PATH)){
		$dir_handle = opendir(EXP_FILE_PATH);
		while($file = readdir($dir_handle)){//读取dir条目
			if(is_file(EXP_FILE_PATH.$file)){
				$bq_arr[$file] = EXP_FILE_PATH.$file;
			}
		}
	}
	//本链接
	$uri = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	//路径导航
	$module = $Db->find([
		table => [module => 'a',zone => 'b'],
		field => 'a.id mid,b.id zid,a.name mname,b.name zname',
		where => "a.zid = b.id and a.id = {$isExist['mid']}"
	])[0];
/*  帖 */
	
	$count = $Db->count([
		table => ['content'],
		where => "id = {$_GET['cid']} or {$cnt_where} and delete_time is NULL"
	]);
	$rand = rand(1000,9999);
	$p = ceil(($count+1)/PAGE_SIZE);
	$posturl = "details.php?cid={$_GET['cid']}&page={$p}&rand={$rand}#end";
	if($_GET['page']>ceil($count/PAGE_SIZE)){
		header('Location:err.php?id=7');
	}
	$page = page($count,PAGE_SIZE,PAGE_BTN_CNT);
	$con_data = $Db->query("select a.*,b.id uid,b.user,b.nick,b.photo,b.last_time,b.follow_me from content a left join bbs_user b on a.uid = b.id WHERE a.id = {$_GET['cid']} or a.{$cnt_where} and a.delete_time is NULL order by a.time {$page['limit']}");
	$cont_data = [];
	foreach ($con_data as $con_item) {
		//获取文件组
		$con_item['file'] = json_decode($con_item['file'])->path;
		
		//获取关注和粉丝
		$con_me = json_decode($con_item['follow_me'])->uids;
		$con_item['fans'] = count($con_me);

		$con_item = $Db->tohtml($con_item);
		// 替换特殊表情
		preg_match_all('/\[(\d+\.gif)\]/', $con_item['body'], $match);
		$exp_path = EXP_FILE_PATH;
		if($match[1]){
			foreach ($match[1] as $match_item) {
				if(array_key_exists($match_item,$bq_arr)){
					$con_item['body'] = str_replace("[{$match_item}]", "<img src='{$exp_path}{$match_item}'>", $con_item['body']);
				}
			}
		}
		//获取状态
		$con_item['stat'] = (time()-$con_item['last_time'])<1800 ? 'online':'offline';
		

		//获取发帖数
		$con_item['count'] = $Db->count([
			table => ['content'],
			where => "`uid` = {$con_item['uid']}"
		]);
		//获取是否关注、收藏过
		if($user_data){
			$uids_arr = json_decode($user_data['my_follow'])->uids;
			$con_item['followed'] = in_array($con_item['uid'], $uids_arr)?'followed':'';
			$con_item['fol_msg'] = in_array($con_item['uid'], $uids_arr)?'已关注':'未关注';
			$cids_arr = json_decode($user_data['my_follow'])->cids;
			$con_item['collected'] = in_array($con_item['id'], $cids_arr)?'collected':'';
		}
		//获取回复chunk
		if($con_item['reply_id'] != 0 && $isMain){
			$con_item['reply'] = $Db->find([
				table => [content => 'a',bbs_user => 'b'],
				field => 'b.user,b.nick,a.body',
				where => "a.uid = b.id and a.id = {$con_item['reply_id']}"
			])[0];
			$con_item['reply'] = $Db->tohtml($con_item['reply']);
				
			preg_match_all('/\[(\d+\.gif)\]/', $con_item['reply']['body'], $match2);
			
    		if($match2[1]){
    			foreach ($match2[1] as $match_item2) {
    				if(array_key_exists($match_item2,$bq_arr)){
    					$con_item['reply'] = str_replace("[{$match_item2}]", "<img src='{$exp_path}{$match_item2}'>", $con_item['reply']);
    				}
    			}
    		}
		}
		
		array_push($cont_data, $con_item);
	}
	$end_item = end($cont_data);
	$end_item['end'] = 1;
	array_pop($cont_data);
	array_push($cont_data, $end_item);
	
}else{
	header('Location:err.php?id=1');
}

$Db->close();

if($isMobile){
	include './view/details.phone.html';
}else{
	include './view/details.pc.html';
}
include './view/footer.html';
